import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _isUndefined from "lodash/isUndefined";
import _isEmpty from "lodash/isEmpty";
var _excluded = ["lang", "messageCode", "tenantId", "agentId", "dtAgentId"];

var _dec, _dec2, _dec3, _dec4, _dec5, _class, _class2, _class3;

import React, { PureComponent } from 'react';
import { Col, Form, Icon, Input, Modal, Row, Select, Spin } from 'antd';
import { Bind } from 'lodash-decorators';
import { Button as ButtonPermission } from 'components/Permission';
import { isTenantRoleLevel } from 'utils/utils';
import Lov from 'components/Lov';
import intl from 'utils/intl';
import styles from "./index.less?modules";
/**
 * Form.Item 组件label、wrapper长度比例划分
 */

var FormItem = Form.Item;
var Option = Select.Option;
var formLayout = {
  labelCol: {
    span: 4
  },
  wrapperCol: {
    span: 16
  }
};
var formItemLayout = {
  labelCol: {
    span: 7
  },
  wrapperCol: {
    span: 16
  }
};
var formParamsLayout = {
  labelCol: {
    span: 8
  },
  wrapperCol: {
    span: 12
  }
};
/**
 * 发送配置-数据修改滑窗(抽屉)
 * @extends {PureComponent} - React.PureComponent
 * @reactProps {string} anchor - 抽屉滑动位置
 * @reactProps {string} title - 抽屉标题
 * @reactProps {boolean} visible - 抽屉是否可见
 * @reactProps {Function} onOk - 抽屉确定操作
 * @reactProps {Object} form - 表单对象
 * @reactProps {Object} itemData - 操作对象
 * @return React.element
 */

var Drawer = (_dec = Form.create({
  fieldNameProp: null
}), _dec2 = Bind(), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec(_class = (_class2 = (_class3 = /*#__PURE__*/function (_PureComponent) {
  _inherits(Drawer, _PureComponent);

  var _super = _createSuper(Drawer);

  function Drawer() {
    var _this;

    _classCallCheck(this, Drawer);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));
    _this.state = {
      recipientKey: [0],
      // 接收人
      recipientUuid: 1
    };
    return _this;
  }

  _createClass(Drawer, [{
    key: "UNSAFE_componentWillReceiveProps",
    value: // eslint-disable-next-line
    function UNSAFE_componentWillReceiveProps(nextProps) {
      var visible = nextProps.visible;

      if (!visible) {
        this.setState({
          recipientKey: [0],
          recipientUuid: 1
        });
      }
    }
    /**
     * 组件属性定义
     */

  }, {
    key: "saveBtn",
    value:
    /**
     * 确定操作
     */
    function saveBtn() {
      var _this$props = this.props,
          form = _this$props.form,
          onOk = _this$props.onOk,
          onSendOk = _this$props.onSendOk,
          paramsName = _this$props.paramsName;
      var recipientKey = this.state.recipientKey;

      if (onOk) {
        form.validateFields(function (err, values) {
          if (_isEmpty(err)) {
            var messageSender = {};
            var weChatSender = {};
            var dingTalkSender = {};
            var receiverAddressList = [];
            var newReceiverAddressList = [];
            var messageTypeCodeList = [];
            var weChatTypeCodeList = [];
            var dingTalkTypeCodeList = [];
            var userList = []; // 公众号接收人

            var userIdList = []; // 企业微信接收人

            var dtUserIdList = []; // 钉钉接收人

            recipientKey.forEach(function (item) {
              if (values["recipientKey".concat(item)] !== 'WC_O' && values["recipientKey".concat(item)] !== 'WC_E' && values["recipientKey".concat(item)] !== 'DT') {
                newReceiverAddressList.push(_defineProperty({}, values["recipientKey".concat(item)], values["recipientValue".concat(item)]));
              }
            });
            receiverAddressList = newReceiverAddressList.map(function (item) {
              return {
                email: item.EMAIL ? item.EMAIL : undefined,
                phone: item.SMS || item.CALL || item.WEB_HOOK ? item.SMS || item.CALL || item.WEB_HOOK : undefined,
                userId: item.WEB ? item.WEB : undefined,
                // phone: item.CALL ? item.CALL : undefined,
                targetUserTenantId: item.WEB ? 0 : undefined
              };
            });
            recipientKey.forEach(function (item) {
              if (values["recipientKey".concat(item)] === 'WC_O' || values["recipientKey".concat(item)] === 'WC_E') {
                weChatTypeCodeList.push(values["recipientKey".concat(item)]);
              } else if (values["recipientKey".concat(item)] === 'DT') {
                dingTalkTypeCodeList.push(values["recipientKey".concat(item)]);
              } else {
                messageTypeCodeList.push(values["recipientKey".concat(item)]);
              }
            });
            recipientKey.forEach(function (r) {
              if (values["recipientKey".concat(r)] === 'WC_O') {
                userList.push(values["recipientValue".concat(r)]);
              }

              if (values["recipientKey".concat(r)] === 'WC_E') {
                userIdList.push(values["recipientValue".concat(r)]);
              }

              if (values["recipientKey".concat(r)] === 'DT') {
                dtUserIdList.push(values["recipientValue".concat(r)]);
              }
            });
            var args = {};
            var recipientParams = {};

            var lang = values.lang,
                messageCode = values.messageCode,
                tenantId = values.tenantId,
                agentId = values.agentId,
                dtAgentId = values.dtAgentId,
                otherValues = _objectWithoutProperties(values, _excluded);

            Object.keys(otherValues).forEach(function (item) {
              if (item.startsWith('recipientKey') || item.startsWith('recipientValue')) {
                recipientParams[item] = otherValues[item];
              } else {
                args[item] = otherValues[item];
              }
            });
            var data = {};
            paramsName.forEach(function (item) {
              data[item] = {
                value: values[item],
                color: '#000'
              };
            });
            messageSender = {
              lang: lang,
              messageCode: messageCode,
              tenantId: tenantId,
              receiverAddressList: receiverAddressList,
              typeCodeList: messageTypeCodeList,
              args: args
            };
            weChatSender = {
              agentId: agentId,
              lang: lang,
              messageCode: messageCode,
              args: args,
              typeCodeList: weChatTypeCodeList,
              userIdList: userIdList,
              userList: userList,
              data: data
            };
            dingTalkSender = {
              agentId: dtAgentId,
              lang: lang,
              messageCode: messageCode,
              args: args,
              userIdList: dtUserIdList
            }; // FIXME: 没有选择相关类型的时候，不传给后端

            var dataSource = {
              messageSender: messageTypeCodeList && messageTypeCodeList.length > 0 ? messageSender : undefined,
              weChatSender: weChatTypeCodeList && weChatTypeCodeList.length > 0 ? weChatSender : undefined,
              dingTalkSender: dingTalkTypeCodeList && dingTalkTypeCodeList.length > 0 ? dingTalkSender : undefined
            };
            onSendOk(dataSource);
          }
        });
      }
    }
    /**
     * 添加接收者参数
     *
     * @memberof Drawer
     */

  }, {
    key: "addRecipient",
    value: function addRecipient() {
      var _this$state = this.state,
          recipientKey = _this$state.recipientKey,
          recipientUuid = _this$state.recipientUuid;
      var nextKeys = recipientKey.concat(recipientUuid);
      this.setState({
        recipientKey: nextKeys,
        recipientUuid: recipientUuid + 1
      });
    }
    /**
     * 移除接收者键，值
     * @param {*}
     */

  }, {
    key: "removeRecipient",
    value: function removeRecipient(k) {
      var recipientKey = this.state.recipientKey;

      if (recipientKey.length === 1) {
        return;
      }

      this.setState({
        recipientKey: recipientKey.filter(function (key) {
          return key !== k;
        })
      });
    }
    /**
     * 改变语言，获取参数
     */

  }, {
    key: "changeLang",
    value: function changeLang(value) {
      var _this$props2 = this.props,
          onGetParams = _this$props2.onGetParams,
          tableRecord = _this$props2.tableRecord;
      var tenantId = tableRecord.tenantId,
          messageCode = tableRecord.messageCode;
      var langParams = {
        lang: value,
        tenantId: tenantId,
        messageCode: messageCode
      };
      onGetParams(langParams);
    }
    /**
     * render
     * @returns React.element
     */

  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props3 = this.props,
          path = _this$props3.path,
          anchor = _this$props3.anchor,
          visible = _this$props3.visible,
          form = _this$props3.form,
          tableRecord = _this$props3.tableRecord,
          enableService = _this$props3.enableService,
          saving = _this$props3.saving,
          onCancel = _this$props3.onCancel,
          paramsName = _this$props3.paramsName,
          tenantRoleLevel = _this$props3.tenantRoleLevel,
          _this$props3$getParam = _this$props3.getParamsLoading,
          getParamsLoading = _this$props3$getParam === void 0 ? false : _this$props3$getParam;
      var getFieldDecorator = form.getFieldDecorator,
          getFieldValue = form.getFieldValue;
      var recipientKey = this.state.recipientKey;
      var recipientFormItems = recipientKey.map(function (k) {
        return /*#__PURE__*/React.createElement(React.Fragment, {
          key: k
        }, /*#__PURE__*/React.createElement(Row, null, /*#__PURE__*/React.createElement(Col, {
          span: 10
        }, /*#__PURE__*/React.createElement(FormItem, Object.assign({
          required: false,
          label: intl.get('cmsg.common.view.type').d('类型')
        }, formItemLayout), getFieldDecorator("recipientKey".concat(k), {
          rules: [{
            required: true,
            whitespace: true,
            message: intl.get('cpaas.common.validation.notNull', {
              name: intl.get('cmsg.common.view.type').d('类型')
            })
          }]
        })( /*#__PURE__*/React.createElement(Select, {
          allowClear: true
        }, enableService && enableService.map(function (item) {
          return /*#__PURE__*/React.createElement(Option, {
            value: item.typeCode,
            key: item.typeCode
          }, item.typeMeaning);
        }))))), /*#__PURE__*/React.createElement(Col, {
          span: 10,
          offset: 1
        }, /*#__PURE__*/React.createElement(FormItem, Object.assign({
          required: false,
          label: intl.get('cmsg.sendConfig.model.sendConfig.recipient').d('接收人')
        }, formItemLayout), getFieldDecorator("recipientValue".concat(k), {
          rules: [{
            // FIXME: 去除类型校验
            // type: (getFieldValue(`recipientKey${k}`) === 'WEB' && typeof getFieldValue(`recipientValue${k}`) === 'number') ? 'number' : 'string',
            required: // eslint-disable-next-line no-nested-ternary
            getFieldValue("recipientKey".concat(k)) === 'WEB_HOOK' ? false : getFieldValue("recipientKey".concat(k)) !== 'WEB' ? true : _isEmpty(getFieldValue("recipientValue".concat(k))),
            whitespace: getFieldValue("recipientKey".concat(k)) !== 'WEB',
            // 当是站内消息时, 由于 Lov 时 id(不是数字) 会导致校验出错
            message: intl.get('cpaas.common.validation.notNull', {
              name: intl.get('cmsg.sendConfig.model.sendConfig.recipient').d('接收人')
            }),
            // FIXME: 添加transform，只会影响校验，不会影响原始值，都转化为string类型
            transform: function transform(value) {
              return String(value);
            }
          }]
        })(getFieldValue("recipientKey".concat(k)) === 'WEB' ? /*#__PURE__*/React.createElement(Lov, {
          code: isTenantRoleLevel() ? 'CIAM.USER.ORG' : 'CIAM.SITE.USER'
        }) : /*#__PURE__*/React.createElement(Input, null)))), form.getFieldValue("recipientKey".concat(k)) === 'WC_E' && /*#__PURE__*/React.createElement(Col, {
          span: 10
        }, /*#__PURE__*/React.createElement(FormItem, Object.assign({
          required: false,
          label: intl.get('cmsg.sendConfig.model.sendConfig.agentId').d('应用ID')
        }, formItemLayout), getFieldDecorator('agentId', {
          rules: [{
            required: true,
            whitespace: true,
            message: intl.get('cpaas.common.validation.notNull', {
              name: intl.get('cmsg.sendConfig.model.sendConfig.agentId').d('应用ID')
            })
          }]
        })( /*#__PURE__*/React.createElement(Input, null)))), form.getFieldValue("recipientKey".concat(k)) === 'DT' && /*#__PURE__*/React.createElement(Col, {
          span: 10
        }, /*#__PURE__*/React.createElement(FormItem, Object.assign({
          required: false,
          label: intl.get('cmsg.sendConfig.model.sendConfig.agentId').d('应用ID')
        }, formItemLayout), getFieldDecorator('dtAgentId', {
          rules: [{
            required: true,
            whitespace: true,
            message: intl.get('cpaas.common.validation.notNull', {
              name: intl.get('cmsg.sendConfig.model.sendConfig.agentId').d('应用ID')
            })
          }]
        })( /*#__PURE__*/React.createElement(Input, null)))), /*#__PURE__*/React.createElement(Col, {
          span: 1
        }, recipientKey.length > 1 ? /*#__PURE__*/React.createElement(Icon, {
          className: styles.iconButton,
          type: "minus-circle-o",
          onClick: function onClick() {
            return _this2.removeRecipient(k);
          }
        }) : null)));
      });
      return /*#__PURE__*/React.createElement(Modal, {
        destroyOnClose: true,
        width: 520,
        title: intl.get('cmsg.sendConfig.view.title.testSend').d('测试发送'),
        wrapClassName: "ant-modal-sidebar-".concat(anchor),
        transitionName: "move-".concat(anchor),
        visible: visible,
        onOk: this.saveBtn,
        confirmLoading: saving,
        onCancel: onCancel
      }, /*#__PURE__*/React.createElement(Spin, {
        spinning: getParamsLoading
      }, /*#__PURE__*/React.createElement(Form, null, !tenantRoleLevel && /*#__PURE__*/React.createElement(FormItem, Object.assign({
        label: intl.get('cmsg.sendConfig.model.sendConfig.tenantId').d('租户')
      }, formLayout), getFieldDecorator('tenantId', {
        initialValue: tableRecord.tenantId,
        rules: [{
          required: true,
          message: intl.get('cpaas.common.validation.notNull', {
            name: intl.get('cmsg.sendConfig.model.sendConfig.tenantId').d('租户')
          })
        }]
      })( /*#__PURE__*/React.createElement(Lov, {
        code: "CPFM.TENANT",
        disabled: !_isUndefined(tableRecord.tenantId),
        textValue: tableRecord.tenantName
      }))), /*#__PURE__*/React.createElement(FormItem, Object.assign({
        label: intl.get('cmsg.sendConfig.model.sendConfig.messageCode').d('消息代码')
      }, formLayout), getFieldDecorator('messageCode', {
        rules: [{
          required: true,
          message: intl.get('cpaas.common.validation.notNull', {
            name: intl.get('cmsg.sendConfig.model.sendConfig.messageCode').d('消息代码')
          })
        }],
        initialValue: tableRecord.messageCode
      })( /*#__PURE__*/React.createElement(Input, {
        disabled: true
      }))), !_isEmpty(paramsName) ? /*#__PURE__*/React.createElement(FormItem, {
        labelCol: {
          span: 2
        },
        label: intl.get('cmsg.sendConfig.model.sendConfig.params').d('参数')
      }) : '', !_isEmpty(paramsName) ? paramsName && paramsName.map(function (item) {
        return /*#__PURE__*/React.createElement(FormItem, Object.assign({
          label: "".concat(item),
          key: "".concat(item)
        }, formParamsLayout), getFieldDecorator("".concat(item), {})( /*#__PURE__*/React.createElement(Input, null)));
      }) : '', /*#__PURE__*/React.createElement(FormItem, null, /*#__PURE__*/React.createElement(ButtonPermission, {
        permissionList: [{
          code: "".concat(path, ".button.addRecipient"),
          type: 'button',
          meaning: '消息发送配置-添加接收人'
        }],
        icon: "plus",
        type: "primary",
        onClick: this.addRecipient
      }, intl.get('cmsg.sendConfig.view.button.addRecipient').d('添加接收人'))), recipientFormItems)));
    }
  }]);

  return Drawer;
}(PureComponent), _class3.defaultProps = {
  anchor: 'right',
  title: '',
  visible: false,
  onOk: function onOk(e) {
    return e;
  },
  onCancel: function onCancel(e) {
    return e;
  }
}, _class3), (_applyDecoratedDescriptor(_class2.prototype, "saveBtn", [_dec2], Object.getOwnPropertyDescriptor(_class2.prototype, "saveBtn"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "addRecipient", [_dec3], Object.getOwnPropertyDescriptor(_class2.prototype, "addRecipient"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "removeRecipient", [_dec4], Object.getOwnPropertyDescriptor(_class2.prototype, "removeRecipient"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "changeLang", [_dec5], Object.getOwnPropertyDescriptor(_class2.prototype, "changeLang"), _class2.prototype)), _class2)) || _class);
export { Drawer as default };